package blackstar.agent.jvm;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import blackstar.agent.AgentConfig;


/**
 * @author RayWoo (ayufox@gmail.com)
 *
 */
public class KeyWordsJVMNameResolver implements JVMNameResolver
{
	private final static Log LOGGER = LogFactory.getLog(KeyWordsJVMNameResolver.class);

	private Map<String, String> keywords = new LinkedHashMap<String, String>();
	
	private final static String KEYWORD_PREFIX = ".keyword";
	
	public KeyWordsJVMNameResolver() throws FileNotFoundException, IOException
	{
		Properties properties = AgentConfig.getProperties();
		for (Map.Entry entry : properties.entrySet())
        {
			String key = (String) entry.getKey();
        	if (key.endsWith(KEYWORD_PREFIX)  && key.length() > (KEYWORD_PREFIX.length()))
        	{
        		key = key.substring(0, key.length() - KEYWORD_PREFIX.length());
        		LOGGER.info("system[" + key + "] keywords[" + entry.getValue() + "]");
        		keywords.put((String) entry.getValue(), key);
        	}
        }
	}
	
	public String resolve(JMXProxy proxy)
	{
		try
		{
			RuntimeMXBean runtimeMXBean = ManagementFactory.newPlatformMXBeanProxy(proxy
				.getLocalMBeanServerConnection(),
				ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
			
			List<String> jvmArgList = runtimeMXBean.getInputArguments();
			StringBuilder buffer = new StringBuilder();
	        for(String key : jvmArgList)
	        {
	        	buffer.append(key + " ");
	        }
	        
	        String jvmArgs = buffer.toString();
	 
	        LOGGER.info("jvmArgs:" + jvmArgs);
	        
	        for (Map.Entry<String, String> entry : keywords.entrySet())
	        {
	        	if (jvmArgs.contains(entry.getKey()))
	        	{
	        		return (String) entry.getValue();
	        	}
	        }
			
			return null;
		} catch (IOException e)
		{
			LOGGER.info("error when resolve Name for proxy[" + proxy.getPid() + "]", e);
			
			return null;
		}
	}
}
